﻿using System;
using System.IO;
using System.IO.Compression;
using System.Web.Mvc;
using Pay.TO;
using Pay.Core;

namespace Pay.Web.Controllers {
	public class ImageController : Controller {
		[CompressFilter(Duration = 600)]
		public ActionResult Index(string upload_dir, string file_path) {
			//string path = Server.MapPath(Path.Cntent/upload/", upload_dir + "/"));
			//要根据upload_dir不同设置，来判断是否可以生成缩略图，upload_dir设置在全局setting中，待开发
			//images/profile/1600df033761409082490643ef2901a0.jpg_1_400_400_0.jpg
			file_path = file_path.ToLower();
			string ext = Path.GetExtension(file_path);
			string contentType = GetContentType(file_path);
			string invalidRequestFile = "nopic.jpg";

			try {
				int width = 0;//640;
				int height = 0;//428;
				int th_type = 1;
				int quality = 0;//质量
				string oid = string.Empty;
				var file_q = file_path.Split(new string[] { ext }, StringSplitOptions.None);
				if (file_q.Length > 2) {
					oid = file_q[0];
					var arrs = file_q[1].Split('_');
					th_type = int.Parse(arrs[1]);
					width = int.Parse(arrs[2]);
					height = int.Parse(arrs[3]);
					if (arrs.Length == 5)
						quality = int.Parse(arrs[4]);

				} else {
					oid = file_path.Replace(ext, "");
				}

				if (width == 0 && height == 0) {
					var bt = new GridFSHelper().DownloadAsByteArray(oid);
					return File(bt, contentType);
				}

				var uploadHelper = new UploadHelper();
				thumbnail dto = uploadHelper.Get(oid, th_type, width, height);
				if (dto == null) {
					var bt = new GridFSHelper().DownloadAsByteArray(oid);
					var file_byte = Core.ImageHelper.CreateThumbnail(bt, width, height, th_type, quality);

					dto = new thumbnail();
					dto.id = Guid.NewGuid().ToString("N");
					dto.oid = oid;
					dto.file_byte = file_byte;
					dto.width = width;
					dto.height = height;
					dto.type = th_type;
					uploadHelper.Add(dto);
				}

				if (dto != null) {
					return File(dto.file_byte, contentType);
				} else {
					return File(Core.ImageHelper.CreateThumbnail(Server.MapPath(Path.Combine("~/content/", invalidRequestFile)), width, height), "Image/jpeg");
				}

			} catch {
				return HttpNotFound();
			}
		}

		private static string GetContentType(string url) {
			string ext = Path.GetExtension(url);
			switch (ext) {
				case ".gif":
					return "Image/gif";
				case ".jpg":
					return "Image/jpeg";
				case ".png":
					return "Image/png";
				default:
					return "Image/jpeg";
			}
		}

		public class CompressFilterAttribute : OutputCacheAttribute {
			public override void OnActionExecuted(ActionExecutedContext filterContext) {
				string acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
				if (string.IsNullOrEmpty(acceptEncoding)) return;
				var response = filterContext.HttpContext.Response;
				acceptEncoding = acceptEncoding.ToUpperInvariant();

				if (acceptEncoding.Contains("GZIP")) {
					response.AppendHeader("Content-Encoding", "gzip");
					response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
				} else if (acceptEncoding.Contains("DEFLATE")) {
					response.AppendHeader("Content-Encoding", "deflate");
					response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
				}
				base.OnActionExecuted(filterContext);
			}
		}
	}
}